<?php
namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Log;
use app\index\model\vo_video_manage;
use think\Validate;

class Index extends Controller
{
    protected $user;

    public function _initialize()
    {
        //登录校验
        $this->user = login_check();
    }

    public function my_order()
    {
        $order = Db::table('vo_app_order')
            ->where(['memberId' => $this->user['memberId'], 'pay_show' => 0])
            ->order('createTime desc')
            ->select();

        $price = Db::table('vo_price')->where(['state' => 0, 'type' => ['like', "%app_%"]])->select();
        $nobility = Db::table('vo_nobility')->where(['state' => 0])->select();

        $order_list = [];
        foreach ($order as $k => $v) {
            $str = "";
            $price_type = $v['price_type'];

            //爵位支付
            if (strpos($price_type, '100') === 0) {
                $id = str_replace('100', "", $price_type);
                foreach ($nobility as $value) {
                    if ($value['id'] == $id) {
                        $day = $value['hour'] / 24;
                        $str = "购买爵位：{$value['name']}{$day}天";
                    }
                }
            } elseif ($price_type == 2000) {
                $str = "G币专区";
            } else {
                //VIP支付
                foreach ($price as $value) {
                    if ($value['id'] == $price_type) {
                        $day = $value['hour'] / 24;
                        $str = "购买VIP：{$day}天";
                    }
                }
            }

            $v['title'] = $str;
            $order_list[] = $v;
        }

        $this->assign('price', $price);
        $this->assign('order_list', json_encode($order_list));
        return view();
    }

    public function my_order_del()
    {
        $id = input('id');
        if (!$id) {
            return json(['code' => 500, 'msg' => '参数不能为空']);
        }

        Db::table('vo_app_order')->where(['id' => $id])->update(['pay_show' => 1]);

        return json(['code' => 200, 'msg' => '删除成功']);
    }

    public function buy_nobility()
    {
        $list = Db::table('vo_nobility')->where(['state' => 0])->select();
        $this->assign('list', $list);
        return view("");
    }

    public function my_task()
    {
        return view("");
    }

    public function buy_vod_vip()
    {
        $map['state'] = ['=', 0];
        $map['type'] = ['like', "%app_%"];

        $list = Db::table('vo_price')->where($map)->select();
        $nobility = Db::table('vo_config')->field('value')->where(['key' => 'nobility'])->find();
        $vip_str = Db::table('vo_config')->field('value')->where(['key' => 'vip_str'])->find();

        !$nobility && $nobility = 0;
        !$vip_str && $vip_str = "";

        $this->assign('user', $this->user);
        $this->assign('list', $list);
        $this->assign('show', true);
        $this->assign('vip_str', $vip_str['value']);
        $this->assign('nobility', $nobility['value']);
        return view("");
    }

    public function h5_pay()
    {
        $res = Db::table('vo_price')->where('type', 'in', 'app_v1,app_v2,app_v3')->cache(false)->select();

        $price = [];
        foreach ($res as $k => $v) {
            $key = str_replace('app_', '', $v['type']);
            $price[$key] = $v;
        }

        $this->assign('price', $price);
        return view("");
    }

    public function get_vip_video()
    {
        $page = input('page', 1);
        $limit = 30;
        $start = ($page - 1) * $limit;

        $vo_video_manage = new vo_video_manage();
        $data = $vo_video_manage->where(['classId' => 594661, 'isLine' => 0])
            ->order('updateTime desc')
            ->limit($start, $limit)
            ->select();

        $new_data = [];
        foreach ($data as $v) {
            $fileUrl = url_key($v['fileUrl']);
            $new_data[] = [
                'fileId' => $v['fileId'],
                'fileUrl' => $fileUrl,
                'fileName' => $v['fileName'],
                'pic' => $v['pic'],
                'play' => $v['play'],
                'duration' => $v['duration'],
                'love' => $v['love']
            ];
        }

        return json(['code' => 200, 'data' => $new_data]);
    }

    public function pd_task()
    {
        $task_type = input('task_type');

        if (!$task_type) {
            return json(['code' => 500, 'msg' => '参数不能为空']);
        }

        $config = config('points_config')[$task_type];
        $points_type = $config['type'];

        $app_user_id = $this->user['id'];
        if ($task_type == 'pd_sign' || $task_type == 'pd_look30m' || $task_type == 'pd_share') {
            $res = Db::table('vo_points_log')
                ->where(['points_type' => $points_type, 'app_user_id' => $app_user_id])
                ->whereTime('log_add_time', 'today')
                ->find();

            if ($res) {
                return json(['code' => 200, 'msg' => '任务已完成']);
            }
        }

        if ($task_type == 'pd_look10M' || $task_type == 'pd_zan5M') {
            $res = Db::table('vo_points_log')
                ->where(['points_type' => $points_type, 'app_user_id' => $app_user_id])
                ->whereTime('log_add_time', 'month')
                ->find();

            if ($res) {
                return json(['code' => 200, 'msg' => '任务已完成']);
            }
        }

        $points_old = $this->user['user_points'];
        $points_change = $config['change'];
        $user_points = $points_old + $points_change;

        $data = [
            'points_type' => $points_type,
            'points_change' => $points_change,
            'points_old' => $points_old,
            'app_user_id' => $app_user_id,
            'log_add_time' => date('Y-m-d H:i:s', time())
        ];

        Db::table('vo_points_log')->insert($data);

        Db::table('vo_app_user')
            ->where(['id' => $app_user_id])
            ->update(['user_points' => $user_points]);

        return json(['code' => 200, 'msg' => '任务完成']);
    }

    public function vod_points()
    {
        $classId = 597777;

        if (IS_POST) {
            $pageNum = input('pageNum', 1);
            $pageSize = input('pageSize', 10);

            $data = Db::table('vo_video_manage')
                ->field('fileId,fileName,pic,play,duration,love,pay_point')
                ->where(['classId' => $classId, 'isLine' => 0])
                ->order('updateTime', 'desc')
                ->page($pageNum, $pageSize)
                ->select();

            $totalSize = Db::table('vo_video_manage')
                ->where(['classId' => $classId, 'isLine' => 0])
                ->order('updateTime desc')
                ->count();

            ob_start('ob_gzhandler');

            return json(['code' => 200, 'data' => $data, 'totalSize' => $totalSize]);
        }

        $menu = [
            567066 => '腿精',
            568179 => '鬼畜',
            567070 => '开箱',
            567067 => '熟肉',
        ];

        $user_points = $this->user['user_points'];

        $this->assign('menu', $menu);
        $this->assign('classId', $classId);
        $this->assign('user_points', $user_points);
        return view("");
    }

    public function pay_vod_have()
    {
        if (IS_POST) {
            $fileId = input('fid');
            if (!$fileId) {
                return json(['code' => 500, 'msg' => '参数错误']);
            }

            $vod = Db::table('vo_video_manage')->where('fileId', $fileId)->find();
            if (!$vod) {
                return json(['code' => 500, 'msg' => '服务器异常']);
            }

            $log = Db::table('vo_vod_points_log')
                ->where(['fileId' => $fileId, 'uid' => $this->user['id']])
                ->order('vod_exp_date desc')
                ->find();

            if ($log && strtotime($log['vod_exp_date']) > time()) {
                $fileUrl = url_key($vod['fileUrl']);
                return json(['code' => 304, 'msg' => "您已支付", "url" => $fileUrl]);
            }

            $points_pay = $vod['pay_point'];

            //扣除剩余的积分
            $user_points = (int)$this->user['user_points'] - $points_pay;
            if ($user_points < 0) {
                return json(['code' => 501, 'msg' => '您的G币不足请尽快充值']);
            } else {
                return json(['code' => 200, 'msg' => '余额扣币', 'points' => $points_pay]);
            }
        }
    }

    public function pw_contact()
    {
        $id = input('id');
        $memberId = $this->user['memberId'];
        $user = Db::table('vo_app_user')->where(['memberId' => $memberId])->find();
        if (!$user) {
            return json(['code' => 500, 'msg' => '用户不存在']);
        }

        Db::table('pw_girl')->where(['id' => $id])->setInc('girl_look');

        //限定查看记录
        $logs = Db::table('pw_look_log')
            ->whereTime('look_time', 'today')
            ->where(['memberId' => $memberId])->select();

        $max_look = Db::table('vo_config')->where(['key' => 'max_look'])->find();
        $max_look_vip = Db::table('vo_config')->where(['key' => 'max_look_vip'])->find();

        $max_look ? $max_look = $max_look['value'] : $max_look = 2;
        $max_look_vip ? $max_look_vip = $max_look_vip['value'] : $max_look_vip = 10;

        $tmp = [];
        foreach ($logs as $v) {
            $tmp[] = $v['girl_id'];
        }

        $data = Db::table('pw_girl')->field('girl_wx,girl_pwd')->where(['id' => $id])->find();

        if (!in_array($id, $tmp)) {
            //判断用户是不是会员
            if (!$user['vip_exp_date'] || (strtotime($user['vip_exp_date']) <= time())) {
                if (count($logs) >= $max_look) {
                    return json(['code' => 403, 'msg' => "每天只能查看{$max_look}个好友"]);
                }

                //新增查看记录
                Db::table('pw_look_log')->insert([
                    'memberId' => $memberId,
                    'girl_id' => $id,
                    'look_time' => date('Y-m-d H:i:s', time())
                ]);
            } else {
                if (count($logs) >= $max_look_vip) {
                    return json(['code' => 500, 'msg' => "每天只能查看{$max_look_vip}个好友"]);
                }

                //新增查看记录
                Db::table('pw_look_log')->insert([
                    'memberId' => $memberId,
                    'girl_id' => $id,
                    'look_time' => date('Y-m-d H:i:s', time())
                ]);
            }
        }

        return json(['code' => 200, 'data' => $data]);
    }

    //陪玩发布信息
    public function pw_release()
    {
        return view("");
    }

    //提交陪玩信息

    public function pw_submit_girl()
    {
        $data = input('post.');
        $data['add_time'] = date('Y-m-d H:i:s', time());
        $data['memberId'] = $this->user['memberId'];
        $data['girl_tag'] = $data['tag1'];
        if ($data['tag2']) {
            $data['girl_tag'] = $data['girl_tag'] . ',' . $data['tag2'];
        }
        unset($data['tag1']);
        unset($data['tag2']);

        $validate = new Validate([
            'girl_name' => 'require',
            'girl_des' => 'require',
            'girl_tag' => 'require',
            'province' => 'require',
            'city' => 'require',
            'girl_img' => 'require',
            'girl_vod' => 'require',
            'girl_wx' => 'require',
            'girl_pwd' => 'require',
            'memberId' => 'require|unique:pw_girl'


        ],
            [
                'girl_name.require' => '请输入昵称',
                'girl_des.require' => '请输入自我简介',
                'girl_tag.require' => '请选择标签',
                'province.require' => '请选择省',
                'city.require' => '请选择市',
                'girl_img.require' => '请上传头像',
                'girl_vod.require' => '请上传视频',
                'girl_wx.require' => '请输入微信',
                'girl_pwd.require' => '请输入口令',
                'memberId.require' => '请登录',
                'memberId.unique' => '您已提交一次请勿重复提交'

            ]);
        if (!$validate->check($data)) {
            return json(['code' => 500, 'msg' => $validate->getError()]);
        }

        $result = Db::table('pw_girl')->insert($data);
        if ($result) {
            return json(['code' => 200, 'msg' => '新增成功']);

        } else {
            return json(['code' => 500, 'msg' => '新增失败']);

        }


    }

    //重新提交陪玩信息
    public function pw_resubmit_girl()
    {
        if (IS_POST) {
            $data = input('post.');
            $data['add_time'] = date('Y-m-d H:i:s', time());
            $data['memberId'] = $this->user['memberId'];
            $data['girl_tag'] = $data['tag1'];
            if ($data['tag2']) {
                $data['girl_tag'] = $data['girl_tag'] . ',' . $data['tag2'];
            }
            unset($data['tag1']);
            unset($data['tag2']);

            $validate = new Validate([
                'id' => 'require',
                'girl_name' => 'require',
                'girl_des' => 'require',
                'girl_tag' => 'require',
                'province' => 'require',
                'city' => 'require',
                'girl_img' => 'require',
                'girl_vod' => 'require',
                'girl_wx' => 'require',
                'girl_pwd' => 'require',
                'memberId' => 'require|unique:pw_girl'
            ], [
                'id.require' => '请输入id',
                'girl_name.require' => '请输入昵称',
                'girl_des.require' => '请输入自我简介',
                'girl_tag.require' => '请选择标签',
                'province.require' => '请选择省',
                'city.require' => '请选择市',
                'girl_img.require' => '请上传头像',
                'girl_vod.require' => '请上传视频',
                'girl_wx.require' => '请输入微信',
                'girl_pwd.require' => '请输入口令',
                'memberId.require' => '请登录',
                'memberId.unique' => '您已提交一次请勿重复提交'
            ]);

            $data['status'] = 0;
            if (!$validate->check($data)) {
                return json(['code' => 500, 'msg' => $validate->getError()]);
            }

            $result = Db::table('pw_girl')->where(['id' => $data['id'], 'memberId' => $data['memberId']])->update($data);
            if ($result) {
                return json(['code' => 200, 'msg' => '提交成功']);
            } else {
                return json(['code' => 500, 'msg' => '提交失败']);
            }
        }

        $memberId = $this->user['memberId'];
        $girl = Db::table('pw_girl')->field("province,city")
            ->where(array('memberId' => $memberId))->find();

        $this->assign("girl", $girl);
        return view("");
    }

    //获取审核状态
    public function pw_girl_status()
    {
        $memberId = $this->user['memberId'];
        $status = Db::table('pw_girl')->where(array('memberId' => $memberId))->value("status");
        if (is_null($status)) {
            $status = -1;
        }

        return json(['code' => 200, 'data' => $status]);
    }

    //获取妹子信息
    public function pw_girl_info()
    {
        $memberId = $this->user['memberId'];
        if (IS_POST) {
            $girl = Db::table('pw_girl')->where(array('memberId' => $memberId))->find();
            $girl['girl_tag'] = explode(',', $girl['girl_tag']);
            /*
            $where['tag_id'] = array('in',$girl['girl_tag']);

            $girl['girl_tag']=Db::table('pw_girl_tag')->where($where)->field('tag_id,tag_name')->select();
            */
            if (is_null($girl['status'])) {
                $girl['status'] = -1;
            }

            return json(['code' => 200, 'data' => $girl]);
        }

        $girl = Db::table('pw_girl')
            ->field("status,review_content")
            ->where(array('memberId' => $memberId))->find();

        if (is_null($girl)) {
            $this->redirect('/pw_page');
        }

        $this->assign("girl", $girl);
        return view("");
    }

    public function getSignature()
    {
        //获取云点播上传 签名
        $classId = input("classId", 0);
        $procedure = input("procedure", "");

        $conf = config('tencent.wo');
        $SecretId = $conf['TencentCloudSecretId'];
        $SecretKey = $conf['TencentCloudSecretKey'];

        //确定签名的当前时间和失效时间
        $current = time();
        $expired = $current + 86400;  //签名有效期：1天

        //向参数列表填入参数
        $arg_list = array(
            "secretId" => $SecretId,
            "currentTimeStamp" => $current,
            "expireTime" => $expired,
            "random" => rand(),
            "sourceContext" => $classId,
            "procedure" => $procedure
        );

        //计算签名
        $orignal = http_build_query($arg_list);
        $signature = base64_encode(hash_hmac('SHA1', $orignal, $SecretKey, true) . $orignal);

        //对此代码的理解：
        //SecretKey 做加密 + orignal
        //客户端上传的时候 需要带上 SecretKey，由于SecretKey权限过大，需要服务端做加密处理
        //客户端上传时候 带上加密后的签名，腾讯云会根据签名做校验，对发起方进行 鉴权

        return json(['sign' => $signature]);
    }
}